package com.tanhua.app.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.*;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.config.template.AipTemplate;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.model.pojo.*;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UsersService {
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipTemplate aipTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserApi userApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private BlackListApi blackListApi;


    //根据id查询用户详情
    public UserInfoVo findUserInfo(Long userID) {
        //1.根据id查询用户详情
        UserInfo userInfo = userInfoApi.findById(userID);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.updateById(userInfo);
    }

    public SettingsVo findSettings() {
        //1.创建vo对象
        SettingsVo vo = new SettingsVo();
        //2.设置用户id和手机号
        vo.setId(UserHolder.getUserId());
        vo.setPhone(UserHolder.getMobile());
        //3.根据用户id查询陌生人问题
        Question question = questionApi.findById(UserHolder.getUserId());
        //获取陌生人的问题,如果有值,就是用该值,如果没有值,设置默认的问题
        String txt = question == null ? "你喜欢java吗?" : question.getTxt();
        vo.setStrangerQuestion(txt);
        //4.根据用户id查询通知设置数据
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if (settings != null) {
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
            vo.setGonggaoNotification(settings.getGonggaoNotification());
        }
        //5.返回结果
        return vo;
    }

    //保存陌生人问题
    public void questions(String content) {
        //1.根据用户id查询陌生人问题
        Question question = questionApi.findById(UserHolder.getUserId());

        //2.判断数据是否存在
        if (question == null) {
            //不存在就新增
            question = new Question();
            question.setUserId(UserHolder.getUserId());
            question.setTxt(content);
            questionApi.save(question);
        } else {
            //存在就修改
            question.setTxt(content);
            questionApi.update(question);
        }

    }

    //通知设置--保存
    public void notifications(Map param) {
        Boolean likeNotification = (Boolean) param.get("likeNotification");
        Boolean pinglunNotification = (Boolean) param.get("pinglunNotification");
        Boolean gonggaoNotification = (Boolean) param.get("gonggaoNotification");
        //1.根据用户id查询通知设置
        Settings settings = settingsApi.findByUserId(UserHolder.getUserId());
        if (settings == null) {
            //不存在就新增
            settings = new Settings();
            settings.setUserId(UserHolder.getUserId());
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.save(settings);
        } else {
            //存在就更新
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.update(settings);
        }
        //2.判断通知设置数据是否存在

    }

    //分页查询黑名单
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1 调用API分页查询 当前用户 的黑名单用户的用户详情
        Page<UserInfo> pages = userInfoApi.findByPage(UserHolder.getUserId(), page, pagesize);
        List<UserInfo> userInfoList = pages.getRecords();
        return new PageResult(page, pagesize, (int) pages.getTotal(), userInfoList);

        ////2 封装返回的用户详情vos
        //List<UserInfoVo> vos = new ArrayList<>();
        //for (UserInfo userInfo : pages.getRecords()) {
        //    UserInfoVo vo = new UserInfoVo();
        //    BeanUtils.copyProperties(userInfo, vo);
        //    if (userInfo.getAge() != null) {
        //        vo.setAge(userInfo.getAge().toString());
        //    }
        //
        //    vos.add(vo);
        //}
        //
        ////3 封装返回的分页对象
        //return new PageResult(page, pagesize, (int) pages.getTotal(), vos);
    }

    //移除黑名单用户
    public void deleteBlacklist(Long uid) {
        //调用Api，实现删除功能
        blackListApi.deleteBlacklist(UserHolder.getUserId(), uid);
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1.使用阿里oss进行图片上传,返回图片URL地址
        String url = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        //2.使用百度aip进行图片的人脸识别
        boolean detect = aipTemplate.detect(url);
        //3.校验识别的结果,如果校验失败(图片不包含人脸),直接抛异常
        if (!detect) {
            throw new RuntimeException("图片不包含人脸");
        }
        //4.修改用户头像数据
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);

        userInfoApi.updateById(userInfo);
    }

    //修改手机号- 1 发送短信验证码
    public void sendVerificationCode(String mobile) {
        //根据手机号查询用户
        User user = userApi.findByMobile(mobile);
        //判断用户是否存在,如果用户存在,就判断登录是否冻结
        if (user!=null){
            //(冻结范围) 1-冻结登录 2-冻结发言  3-冻结发布动态
            userFreezeService.freezeCheck(user.getId(),"1");
        }
        //1.生成6位数字的短信验证码
        //String code = RandomUtil.randomNumbers(6);
        //2.使用模板类发送短信验证码给手机
        // smsTemplate.sendSms(phone,code);

        String code = "123456";
        //3.把验证码保存到redis中,以后要进行校验   验证码有效时间5分钟
        redisTemplate.opsForValue().set(CHECK_CODE + mobile,code, Duration.ofMinutes(5));
    }
    private String CHECK_CODE="check_code_";

    //    修改手机号 - 2 校验验证码
    public boolean checkVerificationCode(String verificationCode) {
        //1.从redis里面获取验证码
        String redisCode =(String) redisTemplate.opsForValue().get(CHECK_CODE + UserHolder.getMobile());
        //2.比较验证码
        if (StringUtils.isBlank(redisCode) ||! redisCode.equals(verificationCode)){
            throw new BusinessException(ErrorResult.error());
        }else {
            return true;
        }
    }

    public void  updatePhone(String phone) {
        //1.获取需要修改手机号的对象
        Long userId = UserHolder.getUserId();
        //2.调api修改手机号的方法
        userApi.updatePhoneById(userId, phone);

        Map hashMap = new HashMap();
        hashMap.put("id", userId);
        hashMap.put("mobile", phone);
    }





    /*public void phone(String phone) {
        User user = userApi.findByMobile(phone);
        if (user != null) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        user = new User();
        user.setMobile(phone);
        user.setId(UserHolder.getUserId());
        userApi.save(user);
    }*/


}